package com.arlen.controller;

import com.arlen.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @PostMapping("/from")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
        UserDetails user = loginService.loadUserByUsername(username);
        if (user == null){
            return null;
        }
        boolean matches = passwordEncoder.matches(password, user.getPassword());
        if (matches){
            return "success";
        }
        return null;
    }

    @PostMapping("success")
    @PreAuthorize("hasAnyRole('arlen')")
    public String success(){
        return "redirect:main.html";
    }

    @GetMapping("error")
    public String error(){
        return "redirect:error.html";
    }

}
